import React from 'react';
import { Table , Popconfirm, Pagination, Checkbox } from 'antd';
import '../../Order/order.css'
import {observer,inject} from 'mobx-react'
// import Orderdetail from './OrderDetail/OrderDetail'
import {withRouter} from 'react-router-dom'
import ExportJsonExcel from 'js-export-excel'
import * as api from '../../../utils/api'
import axios from '../../../utils/http'
// import { toJS } from 'mobx';

@inject('curOrder')
@observer
class Orderlist extends React.Component {
    constructor(){
        super()
        this.state = {
            columns:[
                {
                  dataIndex: 'isSelected',
                  align:'center',
                  render:(text,record,index)=>{
                    return(
                        <div>
                            {/* {console.log(this.state.curPageData)} */}
                            <Checkbox key={record.isSelected===0?false:true} defaultChecked={record.isSelected===0?false:true}  onChange={()=>this.selectCheckBox(record)}></Checkbox>
                        </div>
                    )
                  }
                },
                {
                    title: '商品名称',
                    dataIndex: 'goodsName',
                    align:'center',
                    render:(text,record,index)=>{
                        return(
                            <div className='imgSize'>
                                <img src={record.goods.goodsPp} alt=""/>
                                <div>
                                    <p>{record.goods.goodsName}</p>
                                    <p>{record.goods.goodsRemarks}</p>
                                    {/* <p>{record.goodShangShi}</p> */}
                                </div>
                            </div>
                        )
                    }
                },
                {
                  title: '订单号',
                  dataIndex: 'orderCode',
                  align:'center',
                  render:(text,record,index)=>{
                    let curOrderClass = record.orderClass
                    switch(curOrderClass){
                      case 0: curOrderClass='普通订单';break;
                      case 1: curOrderClass='团购订单';break;
                      case 2: curOrderClass='秒杀团订单';break;
                      case 3: curOrderClass='抽奖团订单';break;
                      default: curOrderClass='助力免单订单';
                    }
                     return(
                         <div>
                             {record.orderCode} <span className="redTxt">{curOrderClass !== '普通订单'?curOrderClass.slice(0,1):null}</span>
                             {/* {record.orderCode} */}
                         </div>
                     )
                  }
                },
                {
                  title: '下单时间',
                  dataIndex: 'orderOt',
                  align:'center',
                  render:(text,record,index)=>{
                    return(
                      <div>
                          {new Date(record.orderOt).toLocaleString().replace(/\//g,'-').replace(/[\u4e00-\u9fa5]/g,"")}
                      </div>
                    )
                  }
                },
                {
                  title: '收货人',
                  dataIndex: 'memName',
                  align:'center',
                  render:(text,record,index)=>{
                    return(
                      <div>
                          {record.memLocations.memName}
                      </div>
                    )
                  }
                },
                {
                  title: '手机',
                  dataIndex: 'memNum',
                  align:'center',
                  render:(text,record,index)=>{
                    return(
                      <div>
                        {record.memLocations.memNum}
                      </div>
                    )
                  }
                },
                {
                  title: '收获地址',
                  dataIndex: 'memLocation',
                  align:'center',
                  render:(text,record,index)=>{
                    return(
                      <div>
                        {record.memLocations.memLocation}
                      </div>
                    )
                  }
                },
                {
                  title: '原价',
                  dataIndex: 'goodsPrice',
                  align:'center',
                  render:(text,record,index)=>{
                    return(
                      <div>
                          ￥{parseFloat(record.goods.goodsPrice).toFixed(2)}
                      </div>
                    )
                  }
                },
                {
                  title: '数量',
                  dataIndex: 'costinforPd',
                  align:'center',
                  render:(text,record,index)=>{
                    return(
                      <div>
                        {record.costinfor.costinforPq}
                      </div>
                    )
                  }
                },
                {
                  title: '实付金额',
                  dataIndex: 'costinforTaog',
                  align:'center',
                  render:(text,record,index)=>{
                    // console.log(record.costinfor)
                    return(
                      <div>
                          ￥{parseFloat(record.costinfor.costinforAd + record.costinfor.costinforAp + record.costinfor.costinforDc).toFixed(2)}
                          {/* ￥{parseFloat(record.costinfor.costinforTaog).toFixed(2)} */}
                      </div>
                    )
                  }
                },
                {
                  title: '订单状态',
                  dataIndex: 'ordoperStatu',
                  align:'center',
                  width:'12rem',
                  render:(text,record,index)=>{
                      let curDelState = record.orderStatus
                      let curOrderState = record.orderStatu
                      let curOrderClass = record.orderClass
                      switch(curDelState){
                        case 0: curDelState='已删除';break;
                        default: curDelState='';
                      }

                      switch(curOrderState){
                         case 1: curOrderState = '待付款';break;
                         case 2: curOrderState = '待发货';break;  
                         case 3: curOrderState = '待收货';break;  
                         case 4: curOrderState = '待核销';break;  
                         case 5: curOrderState = '待评价';break;  
                         case 6: curOrderState = '已完成';break;  
                         case 7: curOrderState = '已取消';break;  
                         case 8: curOrderState = '已退款';break;  
                         default: curOrderState = '无效';  
                      }
                        switch(curOrderClass){
                          case 0: curOrderClass='普通订单';break;
                          case 1: curOrderClass='团购订单';break;
                          case 2: curOrderClass='秒杀团订单';break;
                          case 3: curOrderClass='抽奖团订单';break;
                          default: curOrderClass='助力免单订单';
                        }
                      return(
                          <div>
                              {
                                // record.orderState === '已取消'?<span className='redTxt'>{record.orderState}</span>:record.orderStateSimple==='普通订单'? <span>{record.orderState}</span> : <span>{record.teamState}</span>
                              curOrderState === '已取消'?<span className='redTxt'>{curOrderState} {curDelState}</span>: <span>{curOrderState}<span className='redTxt'>{curDelState}</span></span>
                                // record.orderClass === 0 ? <span>{curOrderState}</span> : curOrderState === '已取消' ? <span className='redTxt'>{curOrderState}</span> : <span>{record.teamZhuangTai}</span>
                              }
                          </div>
                      )
                  }
                },
                {
                  title: '操作',
                  dataIndex: 'operation',
                  width:'16rem',
                  render: (text, record, index) =>{
                      return (
                          <div>
                              {
                                  record.orderStatus===0? <span></span> :record.orderStatu===7 ? <div className="operateDiv"><span onClick={()=>{
                                      this.openCurHandle(record)}} className="checkBtn">查看</span>
                                      <Popconfirm title="确认删除该行信息吗?" onConfirm={() => this.handleDelete(record)}>
                                         <span className="deleteBtn">删除</span>
                                      </Popconfirm></div> : <span onClick={()=>this.openCurHandle(record)} className="checkBtn">查看</span>
                              }
                          </div>
                      )
                  }
                },
            ],
            data:[//订单列表数据
              {
                costinfor:{},
                memLocations:{},
              }
            ],
            curPageData:[],
            curPage:1,
            curPageSize:3,
            toOrderDetail:false,
            dingDanHaoNum:'',//查询订单号
            shouHuoRen:'',//查询收货人
            dingDanZhuangTai:'',//查询订单状态
        };
    }

    componentDidMount(){
        // 向后台请求订单列表的数据
        this.getOrderList()
    }
    getOrderList = ()=>{
      let _this = this
        axios({
          url:api.GET_ORDERLISTQUERY,
          method:'GET',
        }).then(data=>{
          console.log(data)
          let orderListData = data.data.data
          orderListData = orderListData.map((item,i)=>{
            item.key = i
            item.isSelected = 0
            return item
          })
          // console.log(orderListData)
          let curPage = 1
          let curPageSize = 3
          let start = (curPage-1)*curPageSize
          let end = start + curPageSize
          let curPageData = orderListData.slice(start,end)
          _this.setState({
            curPage:curPage,
            curPageSize:curPageSize,
            curPageData:curPageData,
            data:orderListData
          })
        })
    }
    selectCheckBox=(isSelectItem)=>{
      // console.log(isSelectItem)
      let curRowItem = {...isSelectItem}
      if(isSelectItem.isSelected === 0){
        curRowItem.isSelected = 1
      }else{
        curRowItem.isSelected = 0
      }

      let dataArr = [...this.state.data]
      dataArr.forEach((item,i)=>{
          if(item.orderId === isSelectItem.orderId){
            dataArr.splice(i,1,curRowItem)
          }
        })
      // console.log(dataArr)
      // console.log(this.state.curPageData)

      let curPageSize = 3
      let start = (this.state.curPage-1)*curPageSize
      let end = start + curPageSize
      let curPageData = dataArr.slice(start,end)
      this.setState({
          data:dataArr,
          curPageData:curPageData
      })
    }
    reSetChecked=()=>{
      let dataArr = [...this.state.data]
      dataArr.forEach(item=>{
        if(item.isSelected === 1){
          item.isSelected = 0
        }
      })
      this.setState({
        data:dataArr
      })
    }
  //奇偶行的样式
  getRowClassName = (record, index) => {
    let className = '';
    className = index % 2 === 0 ? 'oddRowStyle' : 'evenRowStyle';
    return className;
  }   
  //查看当前行信息   
  openCurHandle = (curRowData)=>{
    // 将当前订单保存在mobx中
    // this.props.curOrder.saveCurOrder(curRowData.orderId)
    this.props.curOrder.saveCurOrder(curRowData)
    this.props.history.push('/Home/dingDan/Orderlist/Orderdetail')
  }
  //删除当前行   
  handleDelete = (curRowData)=>{
    // console.log(curRowData)
    // 发起请求  删除当前行的数据
    axios({
      url:api.GET_DELETORDERLISTBYID,
      method:'GET',
      params:{
        orderId:curRowData.orderId
      }
    }).then(()=>{
      this.getOrderList()
    })
  }
  // 选中所有
  allCheckChange = (e)=>{
    // console.log(e.target.checked)
    let dataArr = [...this.state.data]
    if(e.target.checked){
      dataArr.forEach(item=>{
        if(item.isSelected !== 1){
          item.isSelected = 1
        }
      })
    }else{
      dataArr.forEach(item=>{
        if(item.isSelected !== 0){
          item.isSelected = 0
        }
      })
    }
    this.setState({
      data:dataArr
    })
  }
  curPageAllCheckChange = (e)=>{
    let dataArr = [...this.state.curPageData]
    if(e.target.checked){
      dataArr.forEach(item=>{
        if(item.isSelected !== 1){
          item.isSelected = 1
        }
      })
    }else{
      dataArr.forEach(item=>{
        if(item.isSelected !== 0){
          item.isSelected = 0
        }
      })
    }
    this.setState({
      curPageData:dataArr
    })
  }
  // 页码改变的时候   
  pageNumChange = (page,pageSize)=>{
    let start = (page-1)*this.state.curPageSize
    let end = start + this.state.curPageSize
    let curPageData = this.state.data.slice(start,end)
    this.setState({
        curPage:page,
        curPageData:curPageData
    })
  }
 //跳到首页
 toPageStart = ()=>{
    let curPage = 1
    let start = (curPage-1)*this.state.curPageSize
    let end = start + this.state.curPageSize
    let curPageData = this.state.data.slice(start,end)
    this.setState({
        curPage:curPage,
        curPageData:curPageData
    })
 }   
// 跳转到尾页
toPageEnd = ()=>{
    let totalPage = Math.ceil(this.state.data.length/this.state.curPageSize)
    let start = (totalPage-1)*this.state.curPageSize
    let end = start + this.state.curPageSize
    let curPageData = this.state.data.slice(start,end)
    this.setState({
        curPage:totalPage,
        curPageData:curPageData
    })
}
// 导出表格
downloadExcel = () => {
    let dataArr = [...this.state.data]
    dataArr = dataArr.filter(item=>{
      return item.isSelected === 1
    })
    // console.log(dataArr)

    let data = dataArr.length>0 ? dataArr : '';//表格数据
    // console.log(data)
    var option={};
    let dataTable = [];
    if (data) {
      for (let i in data) {
        if(data){
          let obj = {
            '订单ID': data[i].orderId,
            '商品名称': data[i].goods.goodsName,
            '订单号': data[i].orderCode,
            '下单时间': new Date(data[i].orderOt).toLocaleString().replace(/\//g,'-').replace(/[\u4e00-\u9fa5]/g,""),
            '收货人': data[i].memLocations.memName,
            '收获人手机号': data[i].memLocations.memNum,
            '收获地址': data[i].memLocations.memLocation,
            '商品总金额': data[i].costinfor.costinforTaog,
          }
          dataTable.push(obj);
        }
      }
    }
    option.fileName = '订单信息列表'
    option.datas=[
      {
        sheetData:dataTable,
        sheetName:'订单信息列表',
        sheetFilter:['订单ID','商品名称','订单号','下单时间','收货人','收获人手机号','收获地址','商品总金额'],
        sheetHeader:['订单ID','商品名称','订单号','下单时间','收货人','收获人手机号','收获地址','商品总金额',],
      }
    ];
   
    var toExcel = new ExportJsonExcel(option); 
    toExcel.saveExcel();        
  }
// 修改订单号查询
changeOrderListNum = (e)=>{
  this.setState({
    dingDanHaoNum:e.target.value
  })
}
changeOrderListShouHuo = (e)=>{
  this.setState({
    shouHuoRen:e.target.value
  })
}
changeOrderListSelectState = (e)=>{
  if(parseFloat(e.target.value) !== 12){
    this.setState({
      dingDanZhuangTai: parseFloat(e.target.value)
    })
  }else{
    this.setState({
      dingDanZhuangTai:''
    })
  }
  
}
searchOrderList = ()=>{
  console.log(this.state.shouHuoRen)
  console.log(this.state.dingDanHaoNum)
  console.log(this.state.dingDanZhuangTai)

  if(this.state.dingDanHaoNum!=='' || this.state.shouHuoRen!=='' || this.state.dingDanZhuangTai!==''){
    axios({
      url:api.GET_QUERYORDERLISTBYNAMEANDCODE,
      method:'GET',
      params:{
        memName:this.state.shouHuoRen,
        orderCode:this.state.dingDanHaoNum,
        orderStatu:this.state.dingDanZhuangTai
      }
    }).then(data=>{
      console.log(data.data.data)
      let dataArr = data.data.data
      dataArr = dataArr.map((item,i)=>{
        item.key = i+1
        item.isSelected = 0
        return item
      })
      let curPage = 1
      let curPageSize = 3
      let start = (curPage-1)*curPageSize
      let end = start + curPageSize
      let curPageData = dataArr.slice(start,end)
      this.setState({
            curPage:curPage,
            curPageSize:curPageSize,
            curPageData:curPageData,
            data:dataArr
      })
    })
  }
}
// 按钮筛选查询
getNewTableList = (val)=>{
  new Promise((resolve,reject)=>{
    this.setState({
      dingDanZhuangTai: parseFloat(val)
    })
    resolve()
  }).then(()=>{
    axios({
      url:api.GET_QUERYORDERLISTBYNAMEANDCODE,
      method:'GET',
      params:{
        memName:'',
        orderCode:'',
        orderStatu:this.state.dingDanZhuangTai
      }
    }).then(data=>{
      // console.log(data.data.data)
      let dataArr = data.data.data
      dataArr = dataArr.map((item,i)=>{
        item.key = i+1
        item.isSelected = 0
        return item
      })
      let curPage = 1
      let curPageSize = 3
      let start = (curPage-1)*curPageSize
      let end = start + curPageSize
      let curPageData = dataArr.slice(start,end)
      this.setState({
            curPage:curPage,
            curPageSize:curPageSize,
            curPageData:curPageData,
            data:dataArr
      })
    })
  })
}
getNewTableDelList = ()=>{
  axios({
    url:api.GET_QUERYORDERLISTBYDEL,
    method:'GET',
  }).then(data=>{
    console.log(data)
    let dataArr = data.data.data
    dataArr = dataArr.map((item,i)=>{
      item.key = i+1
      item.isSelected = 0
      return item
    })
    let curPage = 1
    let curPageSize = 3
    let start = (curPage-1)*curPageSize
    let end = start + curPageSize
    let curPageData = dataArr.slice(start,end)
    this.setState({
          curPage:curPage,
          curPageSize:curPageSize,
          curPageData:curPageData,
          data:dataArr
    })
  })
}
  render() {
    return (
      <div className="orderListBoxAllClass">
        {/* {this.state.toOrderDetail === false ? */}
          <div className='orderListBoxStyle'>
              <h1>订单列表</h1>
              <div className="tabClass">
                  <ul>
                      <li onClick={()=>this.getOrderList()}>全部</li>
                      <li onClick={()=>this.getNewTableList(1)}>待付款</li>
                      <li onClick={()=>this.getNewTableList(2)}>待发货</li>
                      <li onClick={()=>this.getNewTableList(4)}>待核销</li>
                      <li onClick={this.getNewTableDelList}>已删除</li>
                  </ul>
              </div>

              {/*  筛选查询  */}
              <div className="searchClass toInlineBlock">
                  <label>订单号<input type="text" name="orderNum" onChange={this.changeOrderListNum}/></label>
                  <label>收货人<input type="text" name="haverstMan" onChange={this.changeOrderListShouHuo}/></label>
                  <select name="" id="" onChange={this.changeOrderListSelectState}>
                      <option value={12}>请选择</option>
                      <option value={1}>待付款</option>
                      <option value={2}>待发货</option>
                      <option value={4}>待核销</option>
                      {/* <option value={11}>已删除</option> */}
                  </select>
                  <button type="button" className="searchBtn" onClick={this.searchOrderList}>搜索</button>
              </div>

              {/* <div style={{ marginBottom: 16 , display:"inline-block"}}>
                <Button type="primary" onClick={this.reSetChecked}>
                  重置
                </Button>
              </div> */}
              {/* <Table rowSelection={rowSelection} columns={this.state.columns} dataSource={this.state.curPageData} pagination={false} rowClassName={this.getRowClassName}/> */}
                <Table columns={this.state.columns} dataSource={this.state.curPageData} pagination={false} rowClassName={this.getRowClassName}/>
                  {/* 分页 */}
              <div className="pagenationbox clearFloat">
                  <div className='allAndChu'>
                      <Checkbox onChange={this.allCheckChange} className='blueTxt'>全选</Checkbox>
                      <Checkbox onChange={this.curPageAllCheckChange} className='blueTxt'>选中当前页</Checkbox>
                      <span className="checkBtn" onClick={this.downloadExcel}>导出</span>
                      <span className="deleteBtn">打印订单</span>
                  </div>
                  <div className='pageNation'>
                      <div className='clearFloat'>
                          <div className='floatLeft'>
                              <Pagination
                                  className='purpleTxt'
                                  total={this.state.data.length}
                                  defaultCurrent={this.state.curPage}
                                  defaultPageSize={this.state.curPageSize}
                                  current={this.state.curPage}
                                  showTotal={total => `共${Math.ceil(this.state.data.length/this.state.curPageSize)}页${total}条记录`}
                                  onChange={this.pageNumChange}
                              />
                          </div>
                          <div className="pageBtnBox">
                              <span className="checkBtn" onClick={this.toPageStart}>首页</span>
                              <span className="checkBtn" onClick={this.toPageEnd}>尾页</span>
                          </div>
                      </div>
                  </div>
              </div>

          </div>
          {/* : 
          <div>
              <Orderdetail onHuiDaoOrder={()=>{
                this.setState({toOrderDetail:false})
                this.props.history.push('/Home/dingDan/Orderlist')
            }}></Orderdetail>
          </div>
        }*/}

      </div>
      
    );
  }
}
export default withRouter(Orderlist);

